import threading, wx
import tomllib
from pathlib import Path

from common.event_dispatcher import EventDispatcher
from config import global_config
from common.api import login
from core.task import Task


def load_tasks(directory: str) -> dict:
    """从指定目录加载所有.toml文件并返回{name: Task}字典"""
    tasks = {}
    dir_path = Path(directory)

    for toml_file in dir_path.glob("*.toml"):
        with open(toml_file, "rb") as f:
            data = tomllib.load(f)

        if "name" not in data:
            print(f"警告：文件 {toml_file} 缺少'name'字段，已跳过")
            continue

        task_name = data["name"]
        tasks[task_name] = Task(**data)

    return tasks


class LoginThread(threading.Thread):
    def run(self):
        # print('开始登录...')
        EventDispatcher().notify_log_message("开始登录...")
        if not global_config.user_token:
            message = '用户token不存在，未登录'
            EventDispatcher().notify_log_message(message)
            return
        else:
            data,status_code = login(global_config.user_token)
            if status_code == 200:
                message = f'登录成功，欢迎您！{data["user"].get("planet_showname","VIP用户") }'
                print(data)
                EventDispatcher().notify_log_message(message)
                EventDispatcher().notify({'id':1, 'show_name': data["user"].get("planet_showname","VIP用户")})


class DownloadThread(threading.Thread):
    def __init__(self, window, data_type):
        super().__init__()
        self.window = window
        self.data_type = data_type
        self._stop_event = threading.Event()

    def run(self):
        #symbols = api.fetch_list(self.data_type)['data']
        symbols = ['510300.SH', '159915.SZ', '518880.SH', '513100.SH',
                           '513500.SH', '159985.SZ', '588000.SH',
                           '513180.SH', '512890.SH', '511880.SH', '161716.SZ', '511260.SH',
                           '513520.SH', '159920.SZ', '513130.SH',
                           ]

        for i, s in enumerate(symbols):
            pass
            #fetch(s,self.data_type)
        #for i in range(self.total):
            if self.stopped():
                break
            #time.sleep(0.01)  # 模拟下载耗时
            progress = i + 1
            log_msg = f"正在更新 {self.data_type} #{progress:04d}/{len(symbols)},{s}...\n"

            # 更新进度和日志
            wx.CallAfter(self.window.update_progress, int(progress/len(symbols)*100), log_msg)
        wx.CallAfter(self.window.update_progress, 100, '数据更新成功完成！')
        if self.data_type == 'etf':
            wx.CallAfter(self.window.enable_update_button)
        if self.data_type == 'bond':
            wx.CallAfter(self.window.enable_update_bond_button)

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()